#!/bin/bash

# Flutter应用版本发布脚本
# 自动更新版本号并创建Git标签

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_success() {
    echo -e "${GREEN}$1${NC}"
}

print_error() {
    echo -e "${RED}$1${NC}"
}

print_warning() {
    echo -e "${YELLOW}$1${NC}"
}

print_info() {
    echo -e "${BLUE}$1${NC}"
}

# 显示帮助信息
show_help() {
    echo "Flutter应用版本发布脚本"
    echo
    echo "用法: $0 [选项] <版本类型>"
    echo
    echo "版本类型:"
    echo "  major     主版本更新 (1.0.0 -> 2.0.0)"
    echo "  minor     次版本更新 (1.0.0 -> 1.1.0)"
    echo "  patch     补丁版本更新 (1.0.0 -> 1.0.1)"
    echo "  custom    自定义版本号"
    echo
    echo "选项:"
    echo "  -v VERSION  指定自定义版本号 (与custom类型一起使用)"
    echo "  -m MESSAGE  发布消息"
    echo "  -d          仅生成版本，不创建Git标签"
    echo "  -p          推送到远程仓库"
    echo "  -b          构建APK/App Bundle"
    echo "  -h          显示帮助信息"
    echo
    echo "示例:"
    echo "  $0 patch                           # 更新补丁版本"
    echo "  $0 minor -m \"添加新功能\"           # 更新次版本并添加消息"
    echo "  $0 custom -v 2.1.0                # 设置自定义版本"
    echo "  $0 major -p -b                    # 更新主版本，推送并构建"
}

# 默认配置
VERSION_TYPE=""
CUSTOM_VERSION=""
RELEASE_MESSAGE=""
DRY_RUN=false
PUSH_TO_REMOTE=false
BUILD_AFTER_RELEASE=false

# 解析命令行参数
parse_arguments() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            -v)
                CUSTOM_VERSION="$2"
                shift 2
                ;;
            -m)
                RELEASE_MESSAGE="$2"
                shift 2
                ;;
            -d)
                DRY_RUN=true
                shift
                ;;
            -p)
                PUSH_TO_REMOTE=true
                shift
                ;;
            -b)
                BUILD_AFTER_RELEASE=true
                shift
                ;;
            -h)
                show_help
                exit 0
                ;;
            major|minor|patch|custom)
                VERSION_TYPE="$1"
                shift
                ;;
            *)
                print_error "未知参数: $1"
                show_help
                exit 1
                ;;
        esac
    done
    
    if [ -z "$VERSION_TYPE" ]; then
        print_error "错误: 必须指定版本类型"
        show_help
        exit 1
    fi
    
    if [ "$VERSION_TYPE" = "custom" ] && [ -z "$CUSTOM_VERSION" ]; then
        print_error "错误: 使用custom类型时必须指定版本号 (-v)"
        exit 1
    fi
}

# 验证环境
check_environment() {
    # 检查是否在Git仓库中
    if ! git rev-parse --git-dir > /dev/null 2>&1; then
        print_error "错误: 当前目录不是Git仓库"
        exit 1
    fi
    
    # 检查是否有未提交的更改
    if [ "$DRY_RUN" = false ] && ! git diff-index --quiet HEAD --; then
        print_error "错误: 有未提交的更改，请先提交或暂存"
        exit 1
    fi
    
    # 检查pubspec.yaml
    if [ ! -f "pubspec.yaml" ]; then
        print_error "错误: 未找到pubspec.yaml文件"
        exit 1
    fi
}

# 获取当前版本
get_current_version() {
    CURRENT_VERSION=$(grep "^version:" pubspec.yaml | sed 's/version: *//' | sed 's/+.*//')
    if [ -z "$CURRENT_VERSION" ]; then
        print_error "错误: 无法从pubspec.yaml获取当前版本"
        exit 1
    fi
    print_info "当前版本: $CURRENT_VERSION"
}

# 计算新版本
calculate_new_version() {
    case $VERSION_TYPE in
        major)
            MAJOR=$(echo $CURRENT_VERSION | cut -d. -f1)
            NEW_VERSION="$((MAJOR + 1)).0.0"
            ;;
        minor)
            MAJOR=$(echo $CURRENT_VERSION | cut -d. -f1)
            MINOR=$(echo $CURRENT_VERSION | cut -d. -f2)
            PATCH=$(echo $CURRENT_VERSION | cut -d. -f3)
            NEW_VERSION="$MAJOR.$((MINOR + 1)).0"
            ;;
        patch)
            MAJOR=$(echo $CURRENT_VERSION | cut -d. -f1)
            MINOR=$(echo $CURRENT_VERSION | cut -d. -f2)
            PATCH=$(echo $CURRENT_VERSION | cut -d. -f3)
            NEW_VERSION="$MAJOR.$MINOR.$((PATCH + 1))"
            ;;
        custom)
            NEW_VERSION="$CUSTOM_VERSION"
            ;;
    esac
    
    print_info "新版本: $NEW_VERSION"
}

# 验证版本格式
validate_version() {
    if ! echo "$NEW_VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
        print_error "错误: 版本号格式无效，应为 major.minor.patch (例如: 1.2.3)"
        exit 1
    fi
}

# 更新版本号
update_version() {
    print_info "更新pubspec.yaml中的版本号..."
    
    # 获取当前build number
    CURRENT_BUILD_NUMBER=$(grep "^version:" pubspec.yaml | sed 's/.*+//' || echo "1")
    NEW_BUILD_NUMBER=$((CURRENT_BUILD_NUMBER + 1))
    
    # 更新版本
    sed -i.bak "s/^version:.*/version: $NEW_VERSION+$NEW_BUILD_NUMBER/" pubspec.yaml
    
    if [ $? -eq 0 ]; then
        rm pubspec.yaml.bak
        print_success "✓ 版本号已更新: $NEW_VERSION+$NEW_BUILD_NUMBER"
    else
        print_error "✗ 版本号更新失败"
        exit 1
    fi
}

# 创建Git提交和标签
create_git_tag() {
    if [ "$DRY_RUN" = true ]; then
        print_info "干运行模式: 跳过Git操作"
        return
    fi
    
    # 添加更改
    git add pubspec.yaml
    
    # 创建提交
    COMMIT_MESSAGE="chore: bump version to $NEW_VERSION"
    if [ -n "$RELEASE_MESSAGE" ]; then
        COMMIT_MESSAGE="$COMMIT_MESSAGE

$RELEASE_MESSAGE"
    fi
    
    git commit -m "$COMMIT_MESSAGE"
    print_success "✓ 创建版本提交"
    
    # 创建标签
    TAG_NAME="v$NEW_VERSION"
    TAG_MESSAGE="Release $NEW_VERSION"
    if [ -n "$RELEASE_MESSAGE" ]; then
        TAG_MESSAGE="$TAG_MESSAGE

$RELEASE_MESSAGE"
    fi
    
    git tag -a "$TAG_NAME" -m "$TAG_MESSAGE"
    print_success "✓ 创建Git标签: $TAG_NAME"
}

# 推送到远程
push_to_remote() {
    if [ "$PUSH_TO_REMOTE" = true ] && [ "$DRY_RUN" = false ]; then
        print_info "推送到远程仓库..."
        git push origin HEAD
        git push origin "v$NEW_VERSION"
        print_success "✓ 已推送到远程仓库"
    fi
}

# 构建应用
build_app() {
    if [ "$BUILD_AFTER_RELEASE" = true ]; then
        print_info "构建应用..."
        if [ -f "scripts/build_apk.sh" ]; then
            ./scripts/build_apk.sh -t both -o "releases/v$NEW_VERSION"
            print_success "✓ 应用构建完成"
        else
            print_warning "警告: 未找到构建脚本"
        fi
    fi
}

# 显示发布总结
show_summary() {
    print_success "==== 版本发布完成 ===="
    echo "版本: $CURRENT_VERSION -> $NEW_VERSION"
    echo "构建号: +$NEW_BUILD_NUMBER"
    
    if [ "$DRY_RUN" = false ]; then
        echo "Git标签: v$NEW_VERSION"
        
        if [ "$PUSH_TO_REMOTE" = true ]; then
            echo "状态: 已推送到远程"
        else
            echo "状态: 仅本地更新"
            print_info "使用以下命令推送到远程:"
            print_info "  git push origin HEAD && git push origin v$NEW_VERSION"
        fi
        
        if [ "$BUILD_AFTER_RELEASE" = true ]; then
            echo "构建: 已完成"
        fi
    else
        echo "模式: 干运行 (无实际更改)"
    fi
}

# 主函数
main() {
    print_info "==== Flutter版本发布脚本 ===="
    
    parse_arguments "$@"
    check_environment
    get_current_version
    calculate_new_version
    validate_version
    
    # 显示计划执行的操作
    echo
    print_info "计划执行的操作:"
    echo "  - 更新版本: $CURRENT_VERSION -> $NEW_VERSION"
    if [ "$DRY_RUN" = false ]; then
        echo "  - 创建Git提交和标签"
    fi
    if [ "$PUSH_TO_REMOTE" = true ]; then
        echo "  - 推送到远程仓库"
    fi
    if [ "$BUILD_AFTER_RELEASE" = true ]; then
        echo "  - 构建应用"
    fi
    echo
    
    read -p "是否继续? (y/N): " CONFIRM
    if [[ ! $CONFIRM =~ ^[Yy]$ ]]; then
        print_info "操作已取消"
        exit 0
    fi
    
    update_version
    create_git_tag
    push_to_remote
    build_app
    show_summary
}

# 运行主函数
main "$@"